package com.cn.demo.service;

import com.cn.demo.config.RabbitConst;
import com.cn.demo.entity.LeakyBucket;
import com.cn.demo.entity.SeckillGoods;
import com.cn.demo.entity.SeckillOrder;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 消息监听服务
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/11/14 16:24
 * @projectName test
 */
@Slf4j
@Service
public class RabbitListenerService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private LeakyBucketService leakyBucketService;

    /**
     * 异步创建订单
     * @author: wangjf
     * @createTime: 2019/11/15 17:06
     * @param goods
     * @param channel
     * @param deliveryTag
     * @return void
     */
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitConst.SECKILL_QUEUE), exchange = @Exchange(value = RabbitConst.SECKILL_EXCHANGE), key = RabbitConst.SECKILL_ROUTING_KEY))
    public void seckillHandler(SeckillGoods goods, Channel channel,
                               @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {

        log.info("--------------goods={}", goods);
        SeckillOrder seckillOrder = new SeckillOrder();

        seckillOrder.setGoodsId(goods.getGoodsId());
        seckillOrder.setOrderNo(goods.getId());
        seckillOrder.setUserId(goods.getLockUserId());
        seckillOrder.setQueueId(goods.getQueueId());
        orderService.save(seckillOrder);

        channel.basicAck(deliveryTag, true);
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = RabbitConst.LEAKY_BUCKET_QUEUE), exchange = @Exchange(value = RabbitConst.LEAKY_BUCKET_EXCHANGE), key = RabbitConst.LEAKY_BUCKET_ROUTING_KEY))
    public void leakyBucketHandler(LeakyBucket leakyBucket, Channel channel,
                                   @Header(AmqpHeaders.DELIVERY_TAG) Long deliveryTag) throws IOException {

        leakyBucketService.poolConsumer(leakyBucket);
        channel.basicAck(deliveryTag, true);
    }
}
